package com.shop.mall.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 字符编码过滤器
 *
 * @author admin
 * @version 1.0
 * @date 2019/4/24
 */
@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("javax.servlet.Filter init >>>>>");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("javax.servlet.Filter doFilter >>>>>");
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        filterChain.doFilter(servletRequest, servletResponse);
        // TODO
//        //如果是login.jsp，则不拦截，直接放行，不用进行其他操作
//        if (request.getRequestURI().indexOf("index.jsp") != -1) {
//            filterChain.doFilter(servletRequest, servletResponse);
//        }
//        //因为登录后保存了username，所以可以先检查username判断是否登录
//        if (session.getAttribute("username") != null) {
//            filterChain.doFilter(servletRequest, servletResponse);//已登录，则放行，
//        } else {
//            response.sendRedirect(request.getContextPath()+"/pages/book//login.jsp");//未登录，重定向到登录页面
//            return;
//        }
//        //如果是下面3个url，则不拦截，直接放行，不用进行其他操作
//        if (request.getRequestURI().indexOf("index.jsp") != -1 || request.getRequestURI().indexOf("LoginServlet") != -1 || request.getRequestURI().indexOf("fail.jsp") != -1) {
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }

    }

    @Override
    public void destroy() {
        System.out.println("javax.servlet.Filter destroy >>>>>");
    }
}
